package com.ukao.steward.ui.main;


import android.content.Intent;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import com.ukao.steward.R;
import com.ukao.steward.adapter.HomeAdapter;
import com.ukao.steward.base.MvpFragment;
import com.ukao.steward.bean.HomeBean;
import com.ukao.steward.bean.LogisticsCountBean;
import com.ukao.steward.bean.ValetCountBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.dialog.BingHintDialogFragment;
import com.ukao.steward.eventbus.BatchEvent;
import com.ukao.steward.eventbus.MainEvent;
import com.ukao.steward.listener.DialogSubmitListener;
import com.ukao.steward.pesenter.logistics.HomePesenter;
import com.ukao.steward.ui.logistics.EnterFactory.EnterFactoryTabFragment;
import com.ukao.steward.ui.valetRunners.bingCard.ReadCardFragment;
import com.ukao.steward.ui.valetRunners.createOrder.SeachGuestFragment;
import com.ukao.steward.ui.valetRunners.storage.StorageFragment;
import com.ukao.steward.ui.valetRunners.takeLetter.TakeLetterTabFragment;
import com.ukao.steward.ui.valetRunners.toShop.ToShopFragment;
import com.ukao.steward.ui.valetRunners.waitingOrder.WaitingOrderFragment;
import com.ukao.steward.util.ActivityUtils;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.DensityUtils;
import com.ukao.steward.view.logistics.HomeView;
import com.ukao.steward.widget.MyLRecyclerView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.steward.R.id.right_msg_btn;

public class HomeFragment extends MvpFragment<HomePesenter> implements HomeView {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.left_bar_btn)
    ImageView leftBarBtn;
    @BindView(R.id.recycler_views)
    MyLRecyclerView recyclerView;
    Unbinder unbinder;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.right_msg_btn)
    ImageView rightMsgBtn;
    @BindView(R.id.msg_count)
    TextView msgCount;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private LRecyclerViewAdapter mLRecyclerViewAdapter;
    private ArrayList<HomeBean> mHomeData;
    private HomeAdapter mHomeAdapter;
    private boolean islogistics;
    private LogisticsCountBean mCountBean;
    private ValetCountBean mValetCountBean;
    public String homeName;
    private NfcAdapter nfcAdapter;
    private BingHintDialogFragment mBingHintDialog;
    private int LOGISTICS_SPAN_COUNT=2;
    private int TAKE_SEND_COUNT=3;

    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected HomePesenter createPresenter() {
        return new HomePesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initData();
    }

    @Override
    protected void initView() {
        islogistics = SaveParams.getislogistics();
        initToolbarNav(leftBarBtn);

    }
    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        setStatusBarTintColor(R.color.colorPrimary);
        getMessageCount();
    }
    @Override
    public void onResume() {
        super.onResume();
        if (mBingHintDialog!=null&&mBingHintDialog.getDialog()!=null&&mBingHintDialog.getDialog().isShowing()
                &&nfcAdapter!=null&&nfcAdapter.isEnabled()){
            mBingHintDialog.dismiss();
        }
    }

    @Override
    protected void initListener() {
        super.initListener();
        mLRecyclerViewAdapter.setOnItemClickListener(mOnItemClickListener);
        recyclerView.setOnRefreshListener(mOnRefreshListener);

    }

    private OnRefreshListener mOnRefreshListener = () -> getMessageCount();


    private OnItemClickListener mOnItemClickListener = new OnItemClickListener(){


        @Override
        public void onItemClick(View view, int position) {
            homeName=mHomeAdapter.getDataList().get(position).getName();
            jumpFrament(position);
        }
    };

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(BatchEvent event) {
        switch (event.getMessage()) {
            case againlogin:
                SaveParams.setLogin(false);
                ActivityUtils.JumpAgainActivity(_mActivity);
                break;
            case Msgcount:/*当接收到推送消息的时候就更新界面*/
                getMessageCount();
                break;
        }
    }

    @Subscribe
    public void onEvent(MainEvent event) {
        switch (event.getMessage()) {
            case UN_BUNDLE:
                 String  orderId= (String) event.getData();
                if (CheckUtils.isEmpty(orderId))return;
                mvpPresenter.unlockOrder(orderId);
                break;
        }
    }




    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({right_msg_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
                case right_msg_btn:
                    start(MyMessageFragment.newInstance("", ""), SINGLETASK);
                break;
        }
    }

    /**
     * 取送人员
     */
    private void sendValetRunner() {
         nfcAdapter= NfcAdapter.getDefaultAdapter(_mActivity);
        String[] homeArray;
        homeArray = CheckUtils.isNull(nfcAdapter)&&!CheckUtils.isMIUIDevices()? getResources().getStringArray(R.array.valetRunner_home_item) : getResources().getStringArray(R.array.valetRunner_home_items);
        mHomeData = new ArrayList<>();
        for (int i = 0; i < homeArray.length; i++) {
            int drawable;
            if(CheckUtils.isNull(nfcAdapter)&&!CheckUtils.isMIUIDevices()){
                 drawable=Constant.mhomeSend[i];
            }else {
                 drawable=Constant.mhomeSends[i];
            }
            HomeBean mHomeBean = new HomeBean(homeArray[i], 0, drawable);
            mHomeData.add(mHomeBean);
        }
    }

    /**
     * 物流人员
     */
    private void logistics() {
        mHomeData = new ArrayList<>();
        String[] homeArray = getResources().getStringArray(R.array.logisticsPersonnel_home_item);

        for (int i = 0; i < homeArray.length; i++) {
            HomeBean mHomeBean = new HomeBean(homeArray[i], 0, Constant.mhomeTakes[i]);
            mHomeData.add(mHomeBean);

        }
    }


    /**
     * 跳转响应
     */
    private void jumpFrament(int position) {
        if (islogistics) {   /*物流人员*/
            switch (position) {
                case 0:
                    start(EnterFactoryTabFragment.newInstance(1, mCountBean));
                    break;
                case 1:
                    start(EnterFactoryTabFragment.newInstance(2, mCountBean));
                    break;
                case 2:
                    start(EnterFactoryTabFragment.newInstance(3, mCountBean));
                    break;
                case 3:
                    start(EnterFactoryTabFragment.newInstance(4, mCountBean));
                    break;
            }
        } else {
            switch (homeName) {
                case "绑卡":
                    if (nfcAdapter != null && !nfcAdapter.isEnabled()) {
                        showOpenNfcDiaolog();
                        return;
                    }
                    start(ReadCardFragment.newInstance("", ""));
                    return;
                case "下单":
                    start(SeachGuestFragment.newInstance(true, ""));
                    return;
                case "入库":
                    start(StorageFragment.newInstance("", ""));
                    return;
            }
            switch (position) {/*取送员*/
                case 0:
                    start(WaitingOrderFragment.newInstance("", ""));
                    break;
                case 1:  //取件
                    start(TakeLetterTabFragment.newInstance(1, mValetCountBean));
                    break;
                case 2:  // 送件
                    start(TakeLetterTabFragment.newInstance(2, mValetCountBean));
                    break;
                case 3:
                    start(SeachGuestFragment.newInstance(false, ""));
                    break;
                case 11:
                    start(ToShopFragment.newInstance("",""));
                    break;
            }
        }
    }

    void showOpenNfcDiaolog() {
        mBingHintDialog= BingHintDialogFragment.newInstance(resources.getString(R.string.open_nfc), "");
        mBingHintDialog.setOnSubmitClickListener(mDialogListener);
        mBingHintDialog.show(getChildFragmentManager(),BingHintDialogFragment.class.getName());
    }

    private DialogSubmitListener mDialogListener = new DialogSubmitListener() {
        @Override
        public void onSubmitClick(int parent, Object message) {
            switch (parent){
                case R.id.edit_name_cancel :
                    start(ReadCardFragment.newInstance("", ""));
                    break;
                case R.id.edit_name_submit :
                    if (!nfcAdapter.isEnabled()) {
                        startActivity(new Intent(
                                android.provider.Settings.ACTION_NFC_SETTINGS));
                    }
                    break;
            }
        }
    };



    /**
     * 获取消息数量
     */
    private void getMessageCount() {
        if (islogistics) {
            mvpPresenter.batchCount();
        } else {
            mvpPresenter.takeCount();
        }
    }

    private void initData() {
        if(islogistics) {
            logistics();
            rightMsgBtn.setVisibility(View.GONE);
        } else {
            sendValetRunner();
        }

        if (islogistics){
            LinearLayout.LayoutParams  mParams= (LinearLayout.LayoutParams) recyclerView.getLayoutParams();
            int margins = DensityUtils.dip2px(15);
            mParams.setMargins(margins,margins,margins,margins);
            recyclerView.setLayoutParams(mParams);
        }

        int dividerWith = islogistics ? R.dimen.default_divider_5dp : R.dimen.default_divider_2dp;
        GridItemDecoration divider = new GridItemDecoration.Builder(_mActivity)
                .setHorizontal(dividerWith)
                .setVertical(dividerWith)
                .setColorResource(R.color.transparent)
                .build();
        initGridRecyclerView(recyclerView,islogistics?LOGISTICS_SPAN_COUNT:TAKE_SEND_COUNT);
        mHomeAdapter = new HomeAdapter(_mActivity, mHomeData);
        mHomeAdapter.setPersonnelEnter(islogistics);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mHomeAdapter);
        recyclerView.setAdapter(mLRecyclerViewAdapter);
        recyclerView.addItemDecoration(divider);
        initListener();
    }


    @Override
    public void loadfinish() {
        recyclerView.refreshFinish();
    }


    /**
     * 物流人员消息数量
     */
    @Override
    public void batchCountSucceed(LogisticsCountBean mCountBean) {
        this.mCountBean = mCountBean;
        int mEnterCount = mCountBean.getInSendingCnt();
        int mLeverCount = mCountBean.getOutSendingCnt();
        int orderOutCnt = mCountBean.getOrderOutCnt();
        int orderInCnt = mCountBean.getOrderInCnt();
        HomeBean HomeBean1 = mHomeData.get(0);
        HomeBean HomeBean2 = mHomeData.get(1);
        HomeBean HomeBean3 = mHomeData.get(2);
        HomeBean HomeBean4 = mHomeData.get(3);
        HomeBean1.setMsgCount(mEnterCount);
        HomeBean2.setMsgCount(mLeverCount);
        HomeBean3.setMsgCount(orderInCnt);
        HomeBean4.setMsgCount(orderOutCnt);
        mHomeAdapter.setDataList(mHomeData);

    }
    /**
     * 去送员消息数量
     */
    @Override
    public void ValetCountSucceed(ValetCountBean mValetCountBean) {
        this.mValetCountBean = mValetCountBean;
        msgCount.setVisibility(mValetCountBean.getPushCnt() == 0 ? View.INVISIBLE : View.VISIBLE);
        int mtakeCount = mValetCountBean.getTakeReceiveCnt() + mValetCountBean.getTakeReceivedCnt();
        int msendCount = mValetCountBean.getSendReceiveCnt() + mValetCountBean.getSendReceivedCnt();
        mHomeData.get(0).setMsgCount(mValetCountBean.getWaitCnt());
        mHomeData.get(1).setMsgCount(mtakeCount);
        mHomeData.get(2).setMsgCount(msendCount);
        mHomeAdapter.setDataList(mHomeData);
    }


}
